package com.zjsru.plan2023.oneday;

/**
 * @Author: CookLee
 * @Date: 2023/7/8
 * 两数之和 II - 输入有序数组
 *  给你一个下标从 1 开始的整数数组 numbers
 *
 * 输入：numbers = [2,7,11,15], target = 9
 * 输出：[1,2]
 * 解释：2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2]
 *
 * 输入：numbers = [2,3,4], target = 6
 * 输出：[1,3]
 * 解释：2 与 4 之和等于目标数 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。
 */
public class TwoSum {
    
    /**
     * 二分
     * 固定一个下标开始
     *
     * @param numbers 数字
     * @param target  目标
     * @return {@link int[]}
     */
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.length; i++) {
            //数组下标从1开始
            int left = i + 1;
            int right = numbers.length - 1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                if (numbers[mid] == target - numbers[i]) {
                    return new int[] {i + 1, mid + 1};
                } else if (numbers[mid] < target - numbers[i]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return new int[] {-1, -1};
    }
    
    /**
     * 双指针,模拟
     *
     * @param numbers 数字
     * @param target  目标
     * @return {@link int[]}
     */
    public int[] twoSum2(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left <= right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[] {left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[] {-1, -1};
    }
    
    public static void main(String[] args) {
        TwoSum twoSum = new TwoSum();
        int[] numbers = new int[] {2, 7, 11, 15};
        int target = 9;
        System.out.println(twoSum.twoSum(numbers, target));
    }

    /**
     * 两个sum3
     * 两个sum2，返回的不是下标，是值内容
     *
     * @param target 目标
     * @param price  价格
     * @return {@link int[]}
     */
    public int[] twoSum3(int[] price, int target) {
        int left = 0, right = price.length - 1;
        while (left <= right) {
            int sum = price[left] + price[right];
            if (sum == target) {
                return new int[]{price[left], price[right]};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{-1, -1};
    }
    
}
